package indi.zhifa.study2025.test.rabbitmq.rpc.s1.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import indi.zhifa.engine.core.common.entity.web.RestResponse;
import indi.zhifa.engine.core.common.entity.web.ServiceException;
import indi.zhifa.study2025.test.rabbitmq.common.Constant;
import indi.zhifa.study2025.test.rabbitmq.common.entity.FabRequest;
import indi.zhifa.study2025.test.rabbitmq.rpc.s1.service.IFabRpcService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

@RequiredArgsConstructor
@Component
public class FabRpcServiceImpl implements IFabRpcService {

    private final RabbitTemplate rabbitTemplate;

    @Override
    public Double Fab(FabRequest pFabRequest) throws IOException {

        String replyQueueName = rabbitTemplate.getConnectionFactory()
                .createConnection()
                .createChannel(false)
                .queueDeclare()
                .getQueue();

        // correlationId，自己生成
        String correlationId = UUID.randomUUID().toString();
        MessageProperties props = new MessageProperties();
        props.setReplyTo(replyQueueName);
        props.setCorrelationId(correlationId);
        String jsonBody = JSON.toJSONString(pFabRequest);
        Message message = new Message(jsonBody.getBytes(StandardCharsets.UTF_8), props);
        Message rspMsg = rabbitTemplate.sendAndReceive(Constant.PRC_QUE_REQUEST_S1, message);
        if(null == rspMsg){
            throw new ServiceException("远程调用失败");
        }
        byte[] rspByte = rspMsg.getBody();

        RestResponse<Double> rsp = JSONObject.parseObject(new String(rspByte),new TypeReference<RestResponse<Double>>(){});
        if(rsp.getCode().equals(200)){
            return rsp.getData();
        }else{
            throw new ServiceException(rsp.getCode(),rsp.getMessage());
        }
    }
}
